package com.xinziruo.crawl.interfaces.controller.support;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.xinziruo.crawl.interfaces.controller.support.web.filter.FlashModel;
import com.xinziruo.crawl.infrastruture.util.ExceptionUtils;
import com.xinziruo.crawl.infrastruture.util.JsonUtils;
import com.xinziruo.crawl.infrastruture.util.PathUtils;

/**
 * @author loudyn
 */
public abstract class ControllerSupport extends MultiActionController {
	protected Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * @param success
	 */
	public final void success(String success) {
		FlashModel.setSuccessMessage(success);
	}

	/**
	 * @param error
	 */
	public final void error(String error) {
		FlashModel.setErrorMessage(error);
	}

	/**
	 * @param warning
	 */
	public final void warning(String warning) {
		FlashModel.setWarningMessage(warning);
	}

	/**
	 * @param info
	 */
	public final void info(String info) {
		FlashModel.setInfoMessage(info);
	}

	/**
	 * @param binder
	 */
	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		binder.setIgnoreInvalidFields(true);
		binder.setIgnoreUnknownFields(true);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), false));
	}

	/**
	 * @param response
	 * @param enclosing
	 * @param bean
	 */
	protected void jsonStringEnclosingWith(HttpServletResponse response, String enclosing, Object bean) {
		try {

			response.getWriter().write(String.format(enclosing, JsonUtils.toJsonString(bean)));
		} catch (Exception e) {
			throw ExceptionUtils.toUnchecked(e);
		}
	}

	/**
	 * 
	 * @return
	 */
	protected String getViewPackage() {
		throw new UnsupportedOperationException();
	}

	/**
	 * 
	 * @return
	 */
	protected String listView() {
		return PathUtils.asUnix(getViewPackage()) + "/list";
	}

	/**
	 * 
	 * @return
	 */
	protected String formView() {
		return PathUtils.asUnix(getViewPackage() + "/form");
	}
}
